import React, { useState, useEffect, useCallback } from "react";
import { Table, Pagination, Button, message, Input, Checkbox } from "antd";
import api from "@/fetch";
import { debounce } from "lodash";
import { UserInfo } from "@/interface/globalData";

import "./index.less";

const superManagers = [
  {
    asSuperManager: true,
    name: "是",
  },
  {
    asSuperManager: undefined,
    name: "无",
  },
];

const schoolManagers = [
  {
    asSchoolManager: true,
    name: "是",
  },
  {
    asSchoolManager: undefined,
    name: "无",
  },
];

type SearchUser = Pick<
  UserInfo,
  "schoolName" | "realName" | "asSuperManager" | "asSchoolManager"
>;

const ManageUser: React.FC = () => {
  const [data, setData] = useState<UserInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState<SearchUser>({
    schoolName: "",
    realName: "",
    asSuperManager: undefined,
    asSchoolManager: undefined,
  });

  const fetchData = useCallback(
    debounce(async (currentPage, pageSize, searchParams) => {
      setLoading(true);

      const search: Partial<SearchUser> = {};

      if (searchParams.schoolName !== "") {
        search["schoolName"] = searchParams.schoolName;
      }

      if (searchParams.realName !== "") {
        search["realName"] = searchParams.realName;
      }

      if (typeof searchParams.asSchoolManager === "boolean") {
        search["asSchoolManager"] = searchParams.asSchoolManager;
      }

      if (typeof searchParams.asSuperManager === "boolean") {
        search["asSuperManager"] = searchParams.asSuperManager;
      }

      const params = {
        ...search,
        page: currentPage - 1,
        pageSize,
      };

      try {
        const res = await api.get("/api/v1/admin/user/page", params);
        setData(res.data.result);
        setTotal(res.data.total);
      } catch (error) {
        message.error(error?.message || "获取用户列表失败");
      } finally {
        setLoading(false);
      }
    }, 300),
    [],
  );

  useEffect(() => {
    fetchData(currentPage, pageSize, searchParams);
  }, [currentPage, pageSize, searchParams]);

  const handlePageChange = (newPage: number, newPageSize: number) => {
    currentPage !== newPage && setCurrentPage(newPage);
    pageSize !== newPageSize && setPageSize(newPageSize);
  };

  const handleSearchChange = (
    field: string,
    value: string | boolean | undefined,
  ) => {
    setSearchParams({
      ...searchParams,
      [field]: value,
    });
  };

  // const handleCheckboxChange = (
  //   field: "asSuperManager" | "asSchoolManager",
  // ) => {
  //   setSearchParams({
  //     ...searchParams,
  //     [field]: !searchParams[field],
  //   });
  // };

  const handleSetSuperManager = async (
    info: UserInfo,
    option: "set" | "cancel",
  ) => {
    setLoading(true);
    try {
      await api.post(
        `/api/v1/admin/role/${option === "set" ? "add" : "remove"}`,
        { userId: info.userId },
      );
      message.success(
        option === "set" ? "设为超级管理员成功" : "取消超级管理员成功",
      );
      fetchData(currentPage, pageSize, searchParams);
    } catch (error) {
      message.error(
        error?.message || option === "set"
          ? "设为超级管理员失败"
          : "取消超级管理员失败",
      );
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    { title: "学校Id", dataIndex: "schoolId", key: "schoolId" },
    { title: "学校名", dataIndex: "schoolName", key: "schoolName" },
    { title: "真实姓名", dataIndex: "realName", key: "realName" },
    {
      title: "学校管理员",
      dataIndex: "asSchoolManager",
      key: "asSchoolManager",
      render: (asSchoolManager: boolean) => (asSchoolManager ? "是" : "否"),
    },
    {
      title: "超级管理员",
      dataIndex: "asSuperManager",
      key: "asSuperManager",
      render: (asSuperManager: boolean) => (asSuperManager ? "是" : "否"),
    },
    {
      title: "操作",
      dataIndex: "actions",
      key: "actions",
      render: (_: string, info: UserInfo) => {
        return info.asSuperManager ? (
          <Button danger onClick={() => handleSetSuperManager(info, "cancel")}>
            取消超级管理员
          </Button>
        ) : (
          <Button
            type="primary"
            onClick={() => handleSetSuperManager(info, "set")}
          >
            设为超级管理员
          </Button>
        );
      },
    },
  ];

  return (
    <div className="manage-user-container">
      {!window.useData.getState().userInfo?.token && (
        <h1>没有登录，发送请求都是失败的噢</h1>
      )}
      <div className="manage-user-header">
        <Input
          allowClear
          className="custom-input"
          placeholder="搜索学校名"
          value={searchParams.schoolName}
          onChange={(e) => handleSearchChange("schoolName", e.target.value)}
        />
        <Input
          allowClear
          className="custom-input"
          placeholder="搜索姓名"
          value={searchParams.realName}
          onChange={(e) => handleSearchChange("realName", e.target.value)}
          style={{ marginLeft: "8px" }}
        />
        <Button
          type="primary"
          onClick={() => {
            setCurrentPage(1);
            fetchData(currentPage, pageSize, searchParams);
          }}
          style={{ marginLeft: "8px" }}
        >
          搜索
        </Button>
        <div style={{ marginLeft: "8px" }}>
          学校管理员：
          {schoolManagers.map((s) => (
            <Checkbox
              style={{ marginLeft: "6px" }}
              key={s.name}
              checked={searchParams.asSchoolManager === s.asSchoolManager}
              onChange={() =>
                handleSearchChange("asSchoolManager", s.asSchoolManager)
              }
            >
              {s.name}
            </Checkbox>
          ))}
        </div>
        <div style={{ marginLeft: "8px" }}>
          超级管理员：
          {superManagers.map((s) => (
            <Checkbox
              style={{ marginLeft: "6px" }}
              key={s.name}
              checked={searchParams.asSuperManager === s.asSuperManager}
              onChange={() =>
                handleSearchChange("asSuperManager", s.asSuperManager)
              }
            >
              {s.name}
            </Checkbox>
          ))}
        </div>
      </div>
      <Table
        dataSource={data}
        columns={columns}
        rowKey="userId"
        pagination={false}
        loading={loading}
      />
      <Pagination
        current={currentPage}
        pageSize={pageSize}
        total={total}
        onChange={handlePageChange}
        showSizeChanger
        pageSizeOptions={["10", "20", "50", "100"]}
        style={{ marginTop: "16px", textAlign: "right" }}
      />
    </div>
  );
};

export default ManageUser;
